package one.three.web.two;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class BoundedStack<Item> {

	private Node<Item> first;
	private int n;
	private int max;

	public BoundedStack(int m) {
		first = null;
		n = 0;
		max = m;
	}

	public boolean isEmpty() {
		return first == null;
	}

	public int size() {
		return n;
	}

	public void push(Item item) throws Exception {
		if (n == max) {
			throw new Exception("Full!");
		}
		Node oldfirst = first;
		first = new Node();
		first.item = item;
		first.next = oldfirst;
		n++;
	}

	public Item pop() {
		if (isEmpty()) {
			throw new NoSuchElementException("Stack underflow");
		}
		Item item = (Item) first.item;
		first = first.next;
		n--;
		return item;
	}

	private class Node<Item> {
		Item item;
		Node<Item> next;
	}

	private class LinkedIterator<Item> implements Iterator<Item> {
		private Node<Item> current;

		public LinkedIterator(Node<Item> first) {
			this.current = first;
		}

		@Override
		public boolean hasNext() {

			return current != null;
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}

		@Override
		public Item next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}
			Item item = current.item;
			current = current.next;
			return item;
		}

	}

	public static void main(String[] args) throws Exception {
		BoundedStack<String> s = new BoundedStack<String>(2);
		s.push("a");
		s.push("b");
		s.push("c");
		System.out.println(s.pop());
		System.out.println(s.pop());
	}
}
